package com.qf.controller.servlet;

import com.sun.org.apache.regexp.internal.RE;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * projectName:shopping
 * author:ydw
 * time:2022/4/18 14:56
 * description:
 */
@WebServlet("/baseservlet")
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //1.获取参数中的method
        String param = request.getParameter("method");
        //2.获取要执行的方法对象
        try {
            //通过反射获取要执行的方法
            Method method= this.getClass().getMethod(param,HttpServletRequest.class,HttpServletResponse.class);
            //执行方法(result是方法的返回值)
            //如果mthod是void，则返回null
            Object result =method.invoke(this,request,response);
            if(result==null){
                //认为前端是ajax

            }else {//否则需要请求转发重定向
                String res=result.toString();
                //如果是重定向：约定前缀为redirect
                if(res.startsWith("redirect:")){
                    //对res进行切割
                    String[] arr = res.split(":");
                    if (arr!=null&&arr.length>1) {
                        response.sendRedirect(arr[1]);
                    }
                }else {//如果是转发，约定前缀为forward
                    String[] arr = res.split(":");
                    if (arr!=null&&arr.length>1) {
                        request.getRequestDispatcher(arr[1]).forward(request,response);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用方法失败!");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
